/**
 * Created by maiseries on 2018/1/4.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    Image,
    Animated,
    TouchableWithoutFeedback
} from 'react-native';

import ImagePicker from 'react-native-image-picker'
import Toast from 'react-native-simple-toast'

import FormStatus from './FormStatus'

let self = null;

export default class DefaultUpload extends React.Component {

    static propTypes = {
        style: React.PropTypes.number,
        placeholderImage: React.PropTypes.number,
        updateEvent: React.PropTypes.func.isRequired, //updateEvent = {(uri, progressEvent(event))=>{}}, 见line:81详解
        width: React.PropTypes.number,
        height: React.PropTypes.number,
        control: React.PropTypes.string,
        title: React.PropTypes.string,
        imageValue: React.PropTypes.any
    }

    static defaultProps = {
        placeholderImage: require('../../sources/icon_global_upload.png'),
        width: layout.width(670),
        height: layout.height(234),
        control: FormStatus.EDIT,
        title: '选择...'
    }

    constructor(prop) {
        super(prop);
        this.state = {
            loadingOpacity: new Animated.Value(0),
            loadingWidth: new Animated.Value(0),
            loadingShow: false,
            image: '',
        }
        this.state.image = this.props.imageValue ? this.props.imageValue : this.state.image
    }

    chooseImage() {
        ImagePicker.showImagePicker({
            title: self.props.title,
            cancelButtonTitle:'取消',
            takePhotoButtonTitle:'相机',
            chooseFromLibraryButtonTitle:'从相册选择',
            storageOptions: {
                skipBackup: true,
                path: 'images'
            }
        }, (response) => {
            if (response.didCancel) {
                //ImagePicker cancel
            }
            else if (response.error) {
                //权限不足或者未获取到设备时错误拦截
                Toast.show('操作未授权，请在应用设置中开启权限！')
            }
            else {
                // You can also display the image using data:
                // let source = { uri: 'data:image/jpeg;base64,' + response.data };
                this.setState({
                    image: response.uri,
                    loadingShow: true
                }, () => {
                    self.updateImage(response.uri);
                });
            }
        });
    }

    updateImage(uri) {

        if (self.props.updateEvent) {
            /** 注意
             * updateEvent 父组件向下传递方法updateEvent
             * uri = 获取本地图片的真实uri
             * callback(e) = 父组件处理uri的上传事件时的进度event(回调为 axios 进度参数 progressEvent)
             */
            self.props.updateEvent(uri, () => self.loadingStart(), () => self.loadingEnd())
        }
    }
    //重置 loading & 开始 loading 动画序列
    loadingStart() {
        self.state.loadingWidth.setValue(0);
        self.state.loadingOpacity.setValue(0);
        Animated.timing(self.state.loadingOpacity, {
            duration: 300,
            toValue: 1
        }).start(() => {
            Animated.timing(self.state.loadingWidth, {
                duration: 3000,
                toValue: 1
            }).start()
        })
    }

    loadingEnd() {
        self.setState({
            loadingShow: false
        })
    }

    render() {
        self = this;
        return (
            <View style={[base.rowCC, styles.fieldBox, this.props.style]}>
                <View style={[base.rowCC, styles.outerBox]}>
                    <TouchableWithoutFeedback
                        onPress={() => this.state.loadingShow || this.props.control === FormStatus.SUBMITTING ? {} : this.chooseImage()}>
                        <View>
                            <Image
                                source={this.state.image ? {uri: this.state.image} : this.props.placeholderImage}
                                style={[base.columnCC, styles.imageBox, {
                                    width: this.props.width,
                                    height: this.props.height,
                                }]}
                                resizeMode={'cover'}>
                                {
                                    this.state.loadingShow ?
                                        <Animated.View
                                            style={[base.columnCC, styles.loadingBg, {
                                                opacity: this.state.loadingOpacity
                                            }]}>
                                            <View style={styles.loadingBox}>
                                                <Image
                                                    source={require('../../sources/icon_mine_about.png')}
                                                    style={styles.loadingBack}/>
                                                <Animated.View
                                                    style={[styles.loadingFrontBox, {
                                                        width: this.state.loadingWidth.interpolate({
                                                            inputRange: [0, 1],
                                                            outputRange: [layout.width(0), layout.width(90)]
                                                        })
                                                    }]}>
                                                    <Image
                                                        source={require('../../sources/icon_mine_about.png')}
                                                        style={styles.loadingFront}/>
                                                </Animated.View>
                                            </View>
                                        </Animated.View> :
                                        <View/>
                                }
                            </Image>
                        </View>
                    </TouchableWithoutFeedback>
                </View>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    fieldBox: {
        alignSelf: 'stretch',
    },
    outerBox: {
        flex: 1,
        paddingTop: layout.GAP_VERTICAL_SMALL
    },
    imageBox: {
        borderWidth: layout.LINE_WIDTH,
        borderColor: layout.MAIN_BORDER_COLOR_C1,
        borderRadius: layout.width(4)
    },
    loadingBg: {
        flex: 1,
        alignSelf: 'stretch',
        backgroundColor: 'rgba(255,255,255,0.8)',
        opacity: 0
    },
    loadingBox: {
        width: layout.width(90),
        height: layout.height(90)
    },
    loadingBack: {
        width: layout.width(90),
        height: layout.height(90),
        tintColor: layout.MAIN_AUX_COLOR
    },
    loadingFrontBox: {
        position: 'absolute',
        left: 0,
        top: 0,
        width: layout.width(0),
        height: layout.height(90),
        overflow: 'hidden'
    },
    loadingFront: {
        width: layout.width(90),
        height: layout.height(90)
    },
    loading: {
        width: layout.width(90),
        height: layout.height(90)
    }
});